package com.yuanxiong.getweather.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.yuanxiong.getweather.R;
import com.yuanxiong.getweather.adapter.AreaAdapter;
import com.yuanxiong.getweather.db.Area;
import com.yuanxiong.getweather.gson.AreaInfo;
import com.yuanxiong.getweather.util.HttpUtil;
import com.yuanxiong.getweather.util.Utility;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.yuanxiong.getweather.ui.WeatherActivity.KEY;
import static com.yuanxiong.getweather.ui.WeatherActivity.REQUEST_CODE;

public class AreaActivity extends AppCompatActivity {
    private static final String TAG = "AreaActivity";

    private AreaAdapter mAreaAdapter;
    private ListView mListview;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_area);
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        if (haveLocalData()) {
            loadContent();
        } else {
            //下载数据并保存在数据库
            Toast.makeText(this, "首次加载，请稍等。。。",Toast.LENGTH_SHORT).show();
            requestAreaInfo();
            loadContent();

        }

    }

    private boolean haveLocalData() {
        List<Area> areaList = DataSupport.where("province=?", "上海").find(Area.class);
        return areaList.size() > 0;
    }

    private void loadContent() {
        //List<Area> areaList = DataSupport.where("province=?", "江苏").find(Area.class);
        List<Area> areaList = DataSupport.findAll(Area.class);
        Log.d(TAG, "onCreate: areaList= " + areaList.size());
        mAreaAdapter = new AreaAdapter(this, areaList);

        EditText editText = findViewById(R.id.search_text);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mAreaAdapter != null) {
                    mAreaAdapter.getFilter().filter(s);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mListview = findViewById(R.id.city_list);
        mListview.setAdapter(mAreaAdapter);
        mListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView) view.findViewById(R.id.area_id_code);

                Log.d(TAG, "onItemClick: " + textView.getText());

                Intent i = new Intent();
                i.putExtra("result", textView.getText().toString());
                setResult(REQUEST_CODE, i);
                finish();
            }
        });

    }

    private void requestAreaInfo() {
        String cityUrl = "http://apis.juhe.cn/simpleWeather/cityList?key=" + KEY;

        HttpUtil.sendOKHttpRequest(cityUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                Log.d(TAG, "onResponse: " + responseText);
                final AreaInfo areaInfo = Utility.handleAreaResponse(responseText);
                Log.d(TAG, "onResponse: " + areaInfo.getResult().size());
                saveAreaInfo(areaInfo);

                Log.d(TAG, "onResponse: save ok");
            }
        });
    }

    private void saveAreaInfo(AreaInfo areaInfo) {
        List<AreaInfo.ResultBean> list = areaInfo.getResult();
        for (AreaInfo.ResultBean resultBean : list) {
            Area area = new Area();
            area.setIdCode(resultBean.getId());
            area.setProvince(resultBean.getProvince());
            area.setCity(resultBean.getCity());
            area.setDistrict(resultBean.getDistrict());
            area.save();
        }

    }
}
